<template>
  <lay-card style="min-height:750px">
    <lay-container fluid="true" style="padding: 10px; height: calc(100% - 20px)">
      <lay-layer v-model="visibleTree" :title="visibleTitle" :shade="false" :area="['600px', '700px']">
        <div style="padding: 20px;">
          <VirtualTree
            v-if="visibleTree"
            :scrollHeight="500"
            :showCheckbox="true"
            :checkKeys="checkedKeys"
            @insertTables="relationDBFields"
            @cancelCheck="visibleTree = false"
          ></VirtualTree>
        </div>
      </lay-layer>
      <lay-card height="100%">
        <lay-row :space="space">
          <lay-col span="12">
              <lay-form :model="queryForm" :pane="true">
                  <lay-row>
                    <lay-col md="4">
                        <lay-input v-model="queryForm.function_name" class="form_input" :size="globalSize">
                          <template #prepend>名称</template>
                        </lay-input>
                    </lay-col>
                    <lay-col md="5">
                        <lay-select v-model="queryForm.classify" multiple  class="form_input" :size="globalSize">
                          <lay-select-option :value="item" :label="item" v-for="item in classes"></lay-select-option>
                          <template #prepend>分类</template>
                        </lay-select>
                    </lay-col>
                    <lay-col md="5">
                        <lay-select v-model="queryForm.describe_mode" multiple  class="form_input" :size="globalSize">
                          <lay-select-option :value="item.id" :label="item.name" v-for="item in ruleMethods"></lay-select-option>
                          <template #prepend>方式</template>
                        </lay-select>
                    </lay-col>
                    <lay-col md="3">
                        <lay-input
                          v-model="queryForm.create_user"
                          class="form_input"
                          :size="globalSize"
                        >
                          <template #prepend>创建人</template>
                        </lay-input>
                    </lay-col>
                    <lay-col md="3">
                        <lay-input
                          v-model="queryForm.modify_user"
                          class="form_input"
                          :size="globalSize"
                        >
                          <template #prepend>修改人</template>
                        </lay-input>
                    </lay-col>
                    <lay-col md="4">
                      <lay-button type="normal" @click="queryAllRules" :size="globalSize">查询</lay-button>
                      <lay-button @click="setDefault" :size="globalSize">重置</lay-button>
                      <lay-button @click="editRule('add', {})" type="normal" :size="globalSize">新增</lay-button>
                    </lay-col>
                  </lay-row>
              </lay-form>
            </lay-col>
        </lay-row>
        <lay-row :space="space">
        <lay-col md="24">
            <lay-table
              :size="globalSize"
              ref="tableRef"
              :height="tableHeight"
              :loading="loading"
              :page="page"
              :columns="columns"
              id="id"
              :dataSource="dataSource"
              v-model:selectedKey="selectedKey"
              v-model:selected-keys="selectedKeys"
              @change="changePage"
            >
              <template v-slot:function_id="{ data }">
                <a @click="editRule('query', data)" style="color: blue">{{data.function_id}}</a>
              </template>
              <template v-slot:operator="{ data }">
                <lay-button
                  size="xs"
                  @click="relateDatabase(data)"
                  style="color: blue"
                >关联数据库</lay-button>
                <lay-button
                  size="xs"
                  type="normal"
                  @click="editRule('modify', data)"
                  v-if="data.type !== 'BUILT_IN'"
                >修改</lay-button>
        <!--                    <lay-button size="xs" type="normal" @click="editRule('copy', data)">复制</lay-button>-->
                <lay-button
                  size="xs"
                  type="danger"
                  @click="confirmDeleteRule(data)"
                  v-if="data.type !== 'BUILT_IN'"
                >删除</lay-button>
              </template>
            </lay-table>
        </lay-col>
        <lay-col></lay-col>
        </lay-row>
      </lay-card>
    </lay-container>
  </lay-card>
</template>

<script lang="ts">
export default {
  name: "ConfigRule"
}
</script>

<script lang="ts" setup>
import {layer} from "@layui/layui-vue";
import {h, onBeforeMount, reactive, ref} from "vue";

import {
    countRules,
    deleteRuleApi,
    queryRuleClassApi,
    queryRuleDetailApi,
    queryRules,
    setDefaultRuleApi
} from "../../../api/module/rule";
import AddRule from "../../../components/Rules/AddRule.vue";
import {notify} from "../../../untils/tip";
import {nanoid} from "nanoid";
import VirtualTree from "../../../components/database/VirtualTree.vue";

const tableRef = ref();
const page = reactive({ current: 1, limit: 20, total: 20 });
const selectedKey = ref("");
const selectedKeys = ref([]);

// 定义组件的高度，间距，大小等
const tableHeight = ref('100%');
const space = ref(30);
const globalSize = ref('sm');
const visibleTree = ref(false);

// 规则页面绑定字段
const currentRuleContent = ref();
const checkedKeys = ref([]);
const visibleTitle = ref("规则绑定到数据库字段");

// 查询
onBeforeMount(()=>{
    queryAllRules();
    getRulesClasses();
});

const loading = ref(false);
const columns = ref([
  {"title": "规则编号", "width": "10%", "key": "function_id", "customSlot": "function_id", "sort": "desc"},
  {"title": "规则名称", "width": "15%", "key": "function_name"},
  {"title": "分类", "width": "10%", "key": "classify", "sort": "desc"},
  {"title": "规则描述", "width": "20%", "key": "description"},
  {"title": "创建人", "width": "10%", "key": "create_user", "sort": "desc"},
  {"title": "修改人", "width": "10%", "key": "modify_user", "sort": "desc"},
  {"title": "最后修改时间", "width": "10%", "key": "modify_time", "sort": "desc"},
  {"title": "操作", "width": "15%", "customSlot": "operator", "key": "operator", "fixed": "right",}
]);

const dataSource = ref([]);

const ruleMethods =  ref([
    {id: 5, name: '枚举值', vision: true},
    {id: 6, name: 'SQL语句', vision: true},
    {id: 3, name: '正则表达式', vision: true},
    {id: 0, name: '规则参数固化', vision: true},
    {id: 1, name: '表达式', vision: true},
    {id: 2, name: '条件表达式', vision: true},
]);

const queryForm = reactive({
    function_id: '',
    function_name: '',
    classify: [],
    describe_mode: [],
    create_user: '',
    modify_user: '',
    current: page.current,
    limit: page.limit
});

const setDefault = () => {
  queryForm.function_id = '';
  queryForm.function_name = '';
  queryForm.classify = [];
  queryForm.describe_mode = []
  queryForm.create_user = '';
  queryForm.modify_user = '';
}

const classes = ref([]);

const getRulesClasses = async () => {
  let {result, status, message} = await queryRuleClassApi();
  if(status === 'success'){
    classes.value = result;
  }else {
      layer.msg(message)
  }
};

const deleteRule = async (data: any) => {
    let {result, status, message} = await deleteRuleApi({function_id: data.function_id});
    if(status === 'success'){
        const index = dataSource.value.indexOf(data)
        dataSource.value.splice(index, 1)
    }else {
        layer.msg(message);
    }
};

const confirmDeleteRule = (data: any) => {
    layer.confirm("确定要删除此项规则【" + data.function_id + ':' + data.function_name + '】吗？', {
        btn: [
            {text:'确定', callback: (id: bigint) => {
                deleteRule(data);
                layer.close(id); }
            },
            {text:'取消', callback: (id: bigint) => {
                layer.close(id); }
            }
        ]
    })
};

const editRule = (mode: string, node: any) => {
  layer.open({
    type: 'page',
    title: "编辑仿真规则",
    area: ['70%','70%'],
    content: h(AddRule, {mode, node}),
    maxmin: true,
    shade: false,
    min: (id: bigint) => {
        console.log(`最小化:${id}`)
    },
    full: (id: bigint) => {
        console.log(`最大化:${id}`)
    },
    restore: (id: bigint) => {
        console.log(`重置:${id}`)
    },
    success: (id: bigint) => {
        console.log(`成功:${id}`)
    }
  })
};

const queryAllRules = async () => {
    page.current = 1;
    queryForm.current = page.current;
    loading.value = true;
    let countResult = await countRules(queryForm);
    if(countResult.status === 'success'){
        page.total = countResult.result.total;
        changePage();
    }else {
        layer.msg(countResult.message);
    }
    loading.value = false;
}

const changePage = () => {
    loading.value = true;
    setTimeout(() => {
      getRulesRows();
      loading.value = false;
    }, 500);
};

const getRulesRows = async () => {
    queryForm.current = page.current;
    queryForm.limit = page.limit;
    let {result, status, message} = await queryRules(queryForm);
    if(status === 'success'){
        dataSource.value = result.data_source;
    }else {
        layer.msg(message);
    }
};

const tb_id = ref();


// 规则关联数据库
const relateDatabase = (row: any) => {
  visibleTree.value = !visibleTree.value;
  if(visibleTree.value){
      currentRuleContent.value = row;
      visibleTitle.value = "规则【" + row.function_id + "|" + row.function_name + "】绑定字段";
      checkedKeys.value = row.checkKeys;
  }
}

const relationDBFields = async (data: any, target: string) => {
    const checkedFields = ref([]);
    data.forEach((row: any) => {checkedFields.value.push(row.id)})
    console.log("checkedFields:", checkedFields.value)
    await setFieldRuleMethod(currentRuleContent.value, checkedFields.value);
};

// 添加tag标签值
const addNodeParams = (node: any) => {
    if(node.object === 'field'){
        node.value = "$d{" + node.database + '.' + node.table + '.' + node.field + "}";
        node.tag_type = 'field';
    }else {
        node.value = "${" + node.function_name + "}";
        node.tag_type = 'rule';
    }
    node.no = nanoid();
    node.edit = false;
    node.add = false;
    return node;
};

// 数据源页面，用于设置 单个字段关联规则
const setFieldRuleMethod = async (node: any, res: any) => {
  console.log("node:", node);
  // 规则描述内容
  const params = reactive({
    describe_mode: 0,
    content: {
      defaultRule: '',
      ruleParams: [], // 正则表达式，枚举值，SQL，规则固化，条件表达式
      leftParams: [], // 判断表达式，左侧的值
      midParams: [],  // 判断表达式，中间的判断符号
      rightParams: [] // 判断表达式，右侧的值
    },
    active_path_list: ''
  });
  let response = await queryRuleDetailApi({function_id: node.function_id});
  if(response.status === 'success'){
      params.describe_mode = 0;
      params.active_path_list = res;
      const ruleDetail = addNodeParams(response.result);
      params.content.ruleParams.push(ruleDetail);
      console.log("params:", params);
      let {result, status, message} = await setDefaultRuleApi(params);
      if(status !== 'success'){
        notify(status, "设置规则关联数据库失败：" + message);
      }else {
        notify(status, "设置规则关联数据库成功！");
        visibleTree.value = false;
      }
  }else {
      notify(response.status, "查询规则详情失败:" + response.message);
  }
  return status;
};


</script>

<style scoped>
.form_input {
    width: 90%;
}
</style>